package com.yape.webCrawler.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yape.annotation.CrawlerLog;
import com.yape.po.ChinaIndex;
import com.yape.webCrawler.base.BaseCrawler;
import com.yape.webCrawler.util.JsonUtils;
import org.jsoup.Jsoup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;


import java.io.IOException;
import java.util.*;

/**
 * @Author Hazuki
 * @Date 2025/5/23 上午10:00
 * @Version 1.0
 */
@Component("chinaIndex")
public class StockIndexCrawler extends BaseCrawler {
    private static final String API_URL = "https://push2delay.eastmoney.com/api/qt/clist/get?cb=jQuery_callback&fs=i:1.000001,i:0.399001,i:0.399005,i:0.399006,i:1.000300,i:100.HSI,i:100.HSCEI,i:124.HSCCI,i:100.TWII&fields=f12,f14,f2,f3,f4,f124&pn=1&pz=100&ut=fa5fd1943c7b386f172d6893dbfba10b";
    private static final Logger log = LoggerFactory.getLogger(StockIndexCrawler.class);



    @Override
    @CrawlerLog
    public List<ChinaIndex> execute() throws IOException {
        String jsonpResponse = Jsoup.connect(getApiUrl())
                .ignoreContentType(true)
                .execute()
                .body();

        String jsonString = JsonUtils.extractJsonFromJsonp(jsonpResponse);
        List <ChinaIndex> stockList = parseStockData(jsonString);

        log.info("============爬虫数据表============");
        log.info(String.format("%-15s | %-10s", "股票名称", "价格"));
        log.info("--------------------------------");

        for (ChinaIndex stock : stockList) {
            log.info(String.format("%-15s | %-10.2f",
                stock.getIndexName(), stock.getLatestPrice()));
        }
        return stockList;
    }



    private Map<String, Double> extractStockPrices(String jsonString) throws IOException {
        Map<String, Double> stockPriceMap = new HashMap<>();
        ObjectMapper mapper = new ObjectMapper();

        JsonNode rootNode = mapper.readTree(jsonString);
        JsonNode dataNode = rootNode.get("data");
        JsonNode diffNode = dataNode.get("diff");

        Iterator<Map.Entry<String, JsonNode>> fields = diffNode.fields();
        while (fields.hasNext()) {
            Map.Entry<String, JsonNode> entry = fields.next();
            JsonNode stockInfo = entry.getValue();
            String stockName = stockInfo.get("f14").asText();
            double stockPrice = stockInfo.get("f2").asDouble() / 100.0;

            stockPriceMap.put(stockName, stockPrice);
        }
        return stockPriceMap;
    }

    private List<ChinaIndex> parseStockData(String jsonString) throws IOException {
        List<ChinaIndex> stockList = new ArrayList<>();
        ObjectMapper mapper = new ObjectMapper();

        JsonNode rootNode = mapper.readTree(jsonString);
        JsonNode dataNode = rootNode.get("data");
        JsonNode diffNode = dataNode.get("diff");

        Iterator<Map.Entry<String, JsonNode>> fields = diffNode.fields();
        while (fields.hasNext()) {
            Map.Entry<String, JsonNode> entry = fields.next();
            JsonNode stockInfo = entry.getValue();

            String stockName = stockInfo.get("f14").asText();
            double stockPrice = stockInfo.get("f2").asDouble() / 100.0;

            ChinaIndex stock = ChinaIndex.builder()
                    .indexName(stockName)
                    .latestPrice((float) stockPrice)
                    .build();
            stockList.add(stock);
        }
        return stockList;
    }

    @Override
    protected String getApiUrl() {
        return API_URL;
    }
}